<template>
  <div class="carousel-container">
    <div class="carousel-track" 
         :style="{ transform: `translateX(-${currentPosition}px)` }"
         @touchstart="handleTouchStart"
         @touchmove="handleTouchMove"
         @touchend="handleTouchEnd">
      <div v-for="(image, index) in images" 
           :key="index" 
           class="carousel-item"
           :style="{ width: `${itemWidth}px` }">
        <img :src="image" 
             :alt="`Image ${index + 1}`" 
             @load="() => handleImageLoad(index)"
             @error="() => handleImageError(index)">
      </div>
    </div>
    
    <div class="carousel-controls">
      <button class="control-btn prev" @click="prev" :disabled="!canScrollPrev">
        &#8592;
      </button>
      <button class="control-btn next" @click="next" :disabled="!canScrollNext">
        &#8594;
      </button>
    </div>

    <div class="carousel-indicators">
      <span v-for="(_, index) in pages" 
            :key="index"
            :class="['indicator', { active: currentPage === index }]"
            @click="goToPage(index)">
      </span>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ImageCarousel',
  props: {
    // 接收图片路径数组
    images: {
      type: Array,
      required: true
    },
    // 同时显示的图片数量
    displayCount: {
      type: Number,
      default: 3
    },
    // 自动播放间隔（毫秒）
    autoplayInterval: {
      type: Number,
      default: 3000
    },
    // 是否自动播放
    autoplay: {
      type: Boolean,
      default: true
    },
    // 添加高度属性
    height: {
      type: [String, Number],
      default: '400px'
    }
  },

  data() {
    return {
      currentPosition: 0,
      containerWidth: 0,
      itemWidth: 0,
      currentPage: 0,
      autoplayTimer: null,
      touchStart: null,
      loadedImages: new Set(),
      isInitialized: false
    }
  },

  computed: {
    pages() {
      return Math.ceil(this.images.length / this.displayCount)
    },
    canScrollPrev() {
      return this.currentPosition > 0
    },
    canScrollNext() {
      return this.currentPosition < this.maxPosition
    },
    maxPosition() {
      return Math.max(0, this.itemWidth * (this.images.length - this.displayCount))
    }
  },

  methods: {
    initializeCarousel() {
      if (!this.$el) return
      
      this.containerWidth = this.$el.clientWidth
      this.itemWidth = this.containerWidth / this.displayCount
      this.currentPosition = this.currentPage * this.itemWidth
      this.isInitialized = true
    },

    handleImageLoad(index) {
      this.loadedImages.add(index)
      console.log(`Image ${index} loaded`)
      
      // 当所有图片加载完成时初始化轮播图
      if (this.loadedImages.size === this.images.length && !this.isInitialized) {
        this.initializeCarousel()
      }
    },

    handleImageError(index) {
      console.error(`Failed to load image at index ${index}`)
    },

    prev() {
      if (this.canScrollPrev) {
        this.currentPage = Math.max(0, this.currentPage - 1)
        this.currentPosition = this.currentPage * this.itemWidth
      }
    },

    next() {
      if (this.canScrollNext) {
        this.currentPage = Math.min(this.pages - 1, this.currentPage + 1)
        this.currentPosition = this.currentPage * this.itemWidth
      }
    },

    goToPage(page) {
      this.currentPage = page
      this.currentPosition = this.currentPage * this.itemWidth
    },

    startAutoplay() {
      if (this.autoplay) {
        this.autoplayTimer = setInterval(() => {
          if (this.currentPage >= this.pages - 1) {
            this.currentPage = 0
          } else {
            this.currentPage++
          }
          this.currentPosition = this.currentPage * this.itemWidth
        }, this.autoplayInterval)
      }
    },

    stopAutoplay() {
      if (this.autoplayTimer) {
        clearInterval(this.autoplayTimer)
        this.autoplayTimer = null
      }
    },

    handleTouchStart(e) {
      this.touchStart = e.touches[0].clientX
      this.stopAutoplay()
    },

    handleTouchMove(e) {
      if (!this.touchStart) return
      
      const touch = e.touches[0].clientX
      const diff = this.touchStart - touch
      
      if (Math.abs(diff) > 5) {
        e.preventDefault()
      }
    },

    handleTouchEnd(e) {
      if (!this.touchStart) return
      
      const touch = e.changedTouches[0].clientX
      const diff = this.touchStart - touch
      
      if (diff > 50 && this.canScrollNext) {
        this.next()
      } else if (diff < -50 && this.canScrollPrev) {
        this.prev()
      }
      
      this.touchStart = null
      this.startAutoplay()
    },

    handleResize() {
      this.initializeCarousel()
    }
  },

  mounted() {
    this.startAutoplay()
    window.addEventListener('resize', this.handleResize)
  },

  beforeDestroy() {
    this.stopAutoplay()
    window.removeEventListener('resize', this.handleResize)
  },

  watch: {
    images() {
      this.$nextTick(() => {
        this.initializeCarousel()
      })
    }
  }
}
</script>

<style scoped>
.carousel-container {
  position: relative;
  width: 100%;
  height: v-bind('typeof height === "number" ? `${height}px` : height');
  overflow: hidden;
  background: #f5f5f5;
}

.carousel-track {
  display: flex;
  height: 100%;
  transition: transform 0.5s ease;
  will-change: transform;
}

.carousel-item {
  flex: 0 0 auto;
  height: 100%;
  padding: 0 5px;
  box-sizing: border-box;
}

.carousel-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
  display: block;
}

.carousel-controls {
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  transform: translateY(-50%);
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  pointer-events: none;
}

.control-btn {
  pointer-events: auto;
  background: rgba(255, 255, 255, 0.8);
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  transition: all 0.3s ease;
  z-index: 2;
}

.control-btn:hover {
  background: rgba(255, 255, 255, 0.9);
}

.control-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.carousel-indicators {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 8px;
}

.indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.5);
  cursor: pointer;
  transition: all 0.3s ease;
}

.indicator.active {
  background: white;
  transform: scale(1.2);
}

@media (max-width: 768px) {
  .control-btn {
    width: 30px;
    height: 30px;
    font-size: 16px;
  }
  
  .carousel-indicators {
    bottom: 10px;
  }
  
  .indicator {
    width: 6px;
    height: 6px;
  }
}
</style>
